﻿// <copyright file="LogProviderCsvExtension.cs" company="Ecole Normale Supérieure">
// Released under GPLv2
// </copyright>
// <summary>Provide CSV import feature to ILogProvider.</summary>

namespace Sqwarea.Persistence.Csv
{
    using System;
    using System.Drawing;
    using System.IO;
    using LumenWorks.Framework.IO.Csv;

    /// <summary>
    /// Provide CSV import feature to ILogProvider.
    /// </summary>
    public static class LogProviderCsvExtension
    {
        /// <summary>
        /// Import log list with a CSV file.
        /// Headers :
        /// KingId ; OtherKingId ; LogKind ; Position x ; Position y
        /// </summary>
        /// <param name="logProvider">The game provider</param>
        /// <param name="file">The CSV file</param>
        public static void ImportLogsFromCsv(this ILogProvider logProvider, TextReader file)
        {
            using (CsvReader csv = new CsvReader(file, true))
            {
                int fieldCount = csv.FieldCount;

                if (fieldCount != 5)
                {
                    throw new InvalidDataException();
                }

                while (csv.ReadNextRecord())
                {
                    if (0 > int.Parse(csv[0], Tools.NumberFormat)
                        || 8 < int.Parse(csv[0], Tools.NumberFormat))
                    {
                        throw new InvalidDataException(); 
                    }

                    var position = new Point(
                        int.Parse(csv[3], Tools.NumberFormat),
                        int.Parse(csv[4], Tools.NumberFormat));

                    var log = new Log(
                        int.Parse(csv[0], Tools.NumberFormat),
                        int.Parse(csv[1], Tools.NumberFormat),
                        (LogKind)Enum.Parse(typeof(LogKind), csv[2]),
                        position);

                    logProvider.StoreLog(log);
                }
            }
        }

        /// <summary>
        /// Import log list with a CSV file.
        /// Headers :
        /// KingId ; OtherKingId ; LogKind ; Position x ; Position y
        /// </summary>
        /// <param name="logProvider">The game provider</param>
        /// <param name="file">The CSV file</param>
        public static void ImportLogsFromCsv(this ILogProvider logProvider, string file)
        {
            logProvider.ImportLogsFromCsv(new StreamReader(file));
        }
    }
}